package com.baomidou.mybatisplus.samples.quickstart.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    // 切入点：标记了 @Loggable 注解的方法
    @Pointcut("@annotation(com.baomidou.mybatisplus.samples.quickstart.aop.annotation.Loggable)")
    public void loggableMethods() {}

    // 环绕通知
    @Around("loggableMethods()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取参数
        Object[] args = joinPoint.getArgs();

        logger.info("方法 {} 开始执行，参数：{}", methodName, args);

        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            logger.info("方法 {} 执行完毕，返回值：{}", methodName, result);
            return result;
        } catch (Throwable throwable) {
            logger.error("方法 {} 执行异常：{}", methodName, throwable.getMessage());
            throw throwable;
        }
    }
}
